<template>
  <div class="bigbox">
    <div style="margin-bottom: 40px">
      <h1>用户列表</h1>
    </div>
    <div>
      <input type="text" placeholder="请输入关键内容" v-model="data.keyword" />
      <input type="button" value="查询" @click="queryAllUsers" />
      <input
        style="margin-bottom: 5px"
        type="button"
        value="添加"
        @click="$router.push({ name: 'add' })"
      />
      <table>
        <thead>
          <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>年龄</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="user in data.users" :key="user.id">
            <td>{{ user.id }}</td>
            <td>{{ user.uname }}</td>
            <td>{{ user.uage }}</td>
            <td>
              <input
                type="button"
                value="修改"
                @click="
                  $router.push({ name: 'edit', query: { id: `${user.id}` } })
                "
              />
              |
              <input type="button" value="删除" @click="delUser(user.id)" />
            </td>
          </tr>
        </tbody>
      </table>
    </div>
  </div>
</template>
<script setup>
  import axios from "axios";
  import { onMounted, reactive } from "vue";
  const api = "http://localhost:3000";
  const data = reactive({
    users: {},
    keyword: "",
  });
  //查询所有用户
  function queryAllUsers() {
    console.log(data.keyword);
    axios.get(`${api}/users?keyword=${data.keyword}`).then((res) => {
      data.users = res.data.data;
    });
  }
  //删除用户
  function delUser(id) {
    axios.delete(`${api}/user/${id}`).then(() => {
      console.log("删除成功");
      queryAllBooks();
    });
  }
  onMounted(() => {
    queryAllUsers();
  });
</script>
<style scoped>
  * {
    margin: 0px;
    padding: 0px;
  }
  th {
    line-height: 40px;
  }

  tr,
  td {
    border: 1px solid;
    border-collapse: collapse;
    line-height: 30px;
  }

  table {
    width: 600px;
    border-collapse: collapse;
    text-align: center;
    font-family: cursive;
  }

  .bigbox {
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    width: 100vw;
    height: 100vh;
  }
</style>
